package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.brand.*;
import com.cskaoyan.bean.brand.home.CategoryVO;
import com.cskaoyan.bean.brand.home.MarketCommentVO;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
public class VxGoodsServiceImp implements VxGoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketAdMapper marketAdMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketTopicMapper marketTopicMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketFootprintMapper marketFootprintMapper;


    @Override
    public DetialVO search(MarketGoods marketGoods, BasePageInfo info) {
        //传入页数
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        //
        MarketGoodsExample marketGoodsExample1 = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria1 = marketGoodsExample1.createCriteria();
        if (info.getOrder() != null && info.getOrder() != null) {
            marketGoodsExample.setOrderByClause(info.getSort() + " " + info.getOrder());
        }
        Integer count = (int) marketGoodsMapper.countByExample(marketGoodsExample);
        if (marketGoods.getIsHot() != null) {
            criteria.andIsHotEqualTo(marketGoods.getIsHot());
            criteria1.andIsHotEqualTo(marketGoods.getIsHot());
        }
        if (marketGoods.getIsNew() != null) {
            criteria.andIsNewEqualTo(marketGoods.getIsNew());
            criteria1.andIsNewEqualTo(marketGoods.getIsNew());
        }
        if (marketGoods.getKeywords() != null && !"".equals(marketGoods.getKeywords())) {
            criteria.andKeywordsLike("%" + marketGoods.getKeywords() + "%");
            criteria1.andKeywordsLike("%" + marketGoods.getKeywords() + "%");
        }
        if (marketGoods.getCategoryId() != null && marketGoods.getIsHot() != null || marketGoods.getIsNew() != null || marketGoods.getKeywords() != null) {
            if (marketGoods.getCategoryId() != 0) {
                criteria.andCategoryIdEqualTo(marketGoods.getCategoryId());
            }
        }
        if (marketGoods.getCategoryId() != null && marketGoods.getIsHot() == null && marketGoods.getIsNew() == null &&marketGoods.getKeywords() == null) {
            criteria.andCategoryIdEqualTo(marketGoods.getCategoryId());
        }
        if (marketGoods.getBrandId() != null) {
            criteria.andBrandIdEqualTo(marketGoods.getBrandId());
        }
        List<MarketGoods> marketGoods1 = marketGoodsMapper.selectByExample(marketGoodsExample);

        List<MarketGoods> marketGoods2 = marketGoodsMapper.selectByExample(marketGoodsExample1);
        List<Integer> cateId = new ArrayList<>();
        for (MarketGoods goods : marketGoods2) {
            Integer categoryId = goods.getCategoryId();
            cateId.add(categoryId);
        }
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        if (cateId.size() >= 1) {
            marketCategoryExample.setDistinct(true);
            marketCategoryExample.createCriteria().andIdIn(cateId);
        }
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);


        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(marketGoods1);
        DetialVO data = DetialVO.data(marketGoodsPageInfo);
        data.setList(marketGoods1);
        data.setTotal(count);
        data.setFilterCategoryList(marketCategories);
        return data;
    }

    @Override
    public HomeIndexVO searchAll() {
        //
        PageHelper.startPage(1, 10);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andIsNewEqualTo(true);
        List<MarketGoods> newMarketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        //
        PageHelper.startPage(1, 10);
        MarketGoodsExample marketGoodsExample1 = new MarketGoodsExample();
        marketGoodsExample1.createCriteria().andIsHotEqualTo(true);
        List<MarketGoods> hotMarketGoods = marketGoodsMapper.selectByExample(marketGoodsExample1);
        //
        PageHelper.startPage(1, 3);
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.setDistinct(true);
        marketCouponExample.setOrderByClause("total desc");
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);

        //
        PageHelper.startPage(1, 10);
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        marketCategoryExample.createCriteria().andPidEqualTo(0);
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
        //
        MarketAdExample marketAdExample = new MarketAdExample();
        List<MarketAd> marketAds = marketAdMapper.selectByExample(marketAdExample);
        //
        PageHelper.startPage(1, 4);
        MarketBrandExample marketBrandExample = new MarketBrandExample();
        List<MarketBrand> marketBrands = marketBrandMapper.selectByExample(marketBrandExample);
        //
        PageHelper.startPage(1, 5);
        MarketTopicExample marketTopicExample = new MarketTopicExample();
        List<MarketTopic> marketTopics = marketTopicMapper.selectByExample(marketTopicExample);
        //
        List<FloorGoodsList> lists = new ArrayList<>();
        for (MarketCategory marketCategory : marketCategories) {
            //根据一级分类id得到二级分类
            Integer id = marketCategory.getId();
            MarketCategoryExample marketCategoryExample1 = new MarketCategoryExample();
            marketCategoryExample1.createCriteria().andPidEqualTo(id);
            List<MarketCategory> marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample1);
            //根据二级分类id得到商品信息
            FloorGoodsList floorGoodsList = new FloorGoodsList();
            for (MarketCategory category : marketCategories1) {
                PageHelper.startPage(1, 6);
                MarketGoodsExample marketGoodsExample2 = new MarketGoodsExample();
                marketGoodsExample2.createCriteria().andCategoryIdEqualTo(category.getId());
                List<MarketGoods> marketGoods1 = marketGoodsMapper.selectByExample(marketGoodsExample2);
                if (marketGoods1.size() >= 6) {
                    floorGoodsList.setGoodsList(marketGoods1);
                }
            }
            floorGoodsList.setId(id);
            floorGoodsList.setName(marketCategory.getName());
            lists.add(floorGoodsList);
        }
        return new HomeIndexVO(newMarketGoods, marketCoupons, marketCategories, marketAds, marketBrands, hotMarketGoods, marketTopics, lists);
    }

    @Override
    public int countAllGoods() {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        Integer count = (int) marketGoodsMapper.countByExample(marketGoodsExample);
        return count;
    }

    @Override
    public CategoryVO searchCategory(Integer id) {
        //category Id（有可能一级，有可能二级）
        //根据Id得到所有全部信息
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        marketCategoryExample.createCriteria().andIdEqualTo(id);
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
        //根据一级Id得到所有二级信息
        //判断pid是否为0，true则是一级分类  false则是二级目录
        if (marketCategories.get(0).getPid() == 0) {
            //一级目录 用一级目录id得到所有二级目录信息，然后返回
            MarketCategoryExample marketCategoryExample1 = new MarketCategoryExample();
            marketCategoryExample1.createCriteria().andPidEqualTo(marketCategories.get(0).getId());
            List<MarketCategory> marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample1);
            return new CategoryVO(marketCategories1.get(0), marketCategories1, marketCategories.get(0));
        } else {
            //二级目录 利用二级目录的pid 得到 所有一级目录信息
            MarketCategoryExample marketCategoryExample1 = new MarketCategoryExample();
            marketCategoryExample1.createCriteria().andIdEqualTo(marketCategories.get(0).getPid());
            List<MarketCategory> marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample1);
            //得到 所有二级目录信息
            MarketCategoryExample marketCategoryExample2 = new MarketCategoryExample();
            marketCategoryExample2.createCriteria().andPidEqualTo(marketCategories1.get(0).getId());
            List<MarketCategory> marketCategories2 = marketCategoryMapper.selectByExample(marketCategoryExample2);
            return new CategoryVO(marketCategories.get(0), marketCategories2, marketCategories1.get(0));
//            List<MarketCategory> marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample1);
//
//            return new CategoryVO(marketCategories.get(0), marketCategories1, marketCategories.get(0));
        }
    }

    @Override
    public GoodsDetailVO detail(Integer id) {
        //
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> marketGoodsAttributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        //goods 信息
//        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
//        marketGoodsExample.createCriteria().andIdEqualTo(id);
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        //品牌信息
        MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(marketGoods.getBrandId());

        //评论信息
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        marketCommentExample.createCriteria().andValueIdEqualTo(id);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        //常见问题
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        List<MarketIssue> marketIssues = marketIssueMapper.selectByExample(marketIssueExample);
        //product
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        //spec
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);

        //
        List<MarketCommentVO> marketCommentVOS = new ArrayList<>();
        for (MarketComment marketComment : marketComments) {
            MarketUser marketUser = marketUserMapper.selectByPrimaryKey(marketComment.getUserId());
            MarketCommentVO marketCommentVO = new MarketCommentVO(marketComment.getId(),
                    marketComment.getContent(), marketComment.getAdminContent()
                    , marketComment.getPicUrls(), marketUser.getAvatar(), marketComment.getAddTime(),
                    marketUser.getNickname());
            marketCommentVOS.add(marketCommentVO);
        }
        Comment comment = new Comment(marketComments.size(), marketCommentVOS);
        //建立对象，成员变量list 每一个代表一个选项，比如规格，颜色等等
        List<Specification> specificationList = new ArrayList<>();
        //name用来辨别规格名字是否出现
        String name = "";
//        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
//            if (specificationList.size() >= 1) {
//                for (Specification specification : specificationList) {
//                    if (!marketGoodsSpecification.getSpecification().equals(specification.getName())) {
//                        List<MarketGoodsSpecification> list = new ArrayList<>();
//                        Specification specification1 = new Specification();
//                        specification1.setName(marketGoodsSpecification.getSpecification());
//                        specification1.setValueList(list);
//                        specificationList.add(specification1);
//                        name += marketGoodsSpecification.getSpecification();
//                        break;
//                    }
//                }
//            } else {
//                List<MarketGoodsSpecification> list = new ArrayList<>();
//                Specification specification1 = new Specification();
//                specification1.setName(marketGoodsSpecification.getSpecification());
//                specification1.setValueList(list);
//                specificationList.add(specification1);
//            }
//        }
        //遍历
        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
            //不为空则判断是否存在
            if (specificationList.size() >= 1) {
                if (!name.contains(marketGoodsSpecification.getSpecification())) {
                    List<MarketGoodsSpecification> list = new ArrayList<>();
                    Specification specification1 = new Specification();
                    specification1.setName(marketGoodsSpecification.getSpecification());
                    specification1.setValueList(list);
                    specificationList.add(specification1);
                    name = name + marketGoodsSpecification.getSpecification();
                    break;
                }
                //为空则直接添加
            } else {
                List<MarketGoodsSpecification> list = new ArrayList<>();
                Specification specification1 = new Specification();
                specification1.setName(marketGoodsSpecification.getSpecification());
                specification1.setValueList(list);
                specificationList.add(specification1);
                name += marketGoodsSpecification.getSpecification();
            }
        }
        //遍历添加
        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
            for (Specification specification : specificationList) {
                if (marketGoodsSpecification.getSpecification().equals(specification.getName())) {
                    specification.getValueList().add(marketGoodsSpecification);
                }
            }
        }

        //添加历史足迹
        Subject subject = SecurityUtils.getSubject();
        //直接获取了user对象
        if (subject.getPrincipals() != null) {
            MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
            Integer userId = user.getId();
            MarketFootprint marketFootprint = new MarketFootprint();
            marketFootprint.setGoodsId(id);
            marketFootprint.setUserId(userId);
            marketFootprint.setAddTime(new Date());
            marketFootprint.setUpdateTime(new Date());
            marketFootprintMapper.insert(marketFootprint);
        }
        //历史足迹到此结束

        return new GoodsDetailVO(marketGoodsAttributes, marketBrand, comment, marketGoods,
                marketIssues, marketGoodsProducts, specificationList, true, marketGoods.getShareUrl(), new String[]{}, 1);
    }

    @Override
    public CommonData<MarketGoods> related(Integer id) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        int num = 0;
        for (MarketGoods marketGood : marketGoods) {
            if (marketGood.getId() == id) {
                break;
            }
            num++;
        }
        if ((marketGoods.size() - num) < 8) {
            num -= 7;
        }

        List<MarketGoods> list = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            list.add(marketGoods.get(num + 1));
            num++;
        }
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(marketGoods);
        CommonData data = CommonData.data(marketGoodsPageInfo);
        data.setList(list);
        return data;
    }

}
